package com.freemyleft.left.left_app.mian.index.work.waitingforclass.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;

/**
 * Created by Administrator on 2016/3/11 0011.
 */
public class SetGridHeight {
    public static void setGvHeight(GridView listView, BaseAdapter adapter, int colNum){
        setGvHeight(listView, adapter,colNum, 0);
    }

    public static void setGvHeight(GridView listView, BaseAdapter adapter, int colNum, int hegit){
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = colNum;// listView.getNumColumns();
        int totalHeight = hegit;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            if(listItem!= null){
                listItem.measure(0, 0);
                // 获取item的高度和
                totalHeight += listItem.getMeasuredHeight();
            }

        }
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(0, 0, 0,0 );
        // 设置参数
        listView.setLayoutParams(params);
        adapter.notifyDataSetChanged();
    }
}
